package com.gaeainfo.websocket;

import com.gaeainfo.framework.core.utils.common.GaeaCommonUtil;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by Caven on 2018/1/17.
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> attributes) throws Exception {
        HttpServletRequest request = ((ServletServerHttpRequest) serverHttpRequest).getServletRequest();
        String deptId = request.getParameter("deptId");
        String policeNo = request.getParameter("policeNo");
        if (GaeaCommonUtil.isNullOrEmpty(policeNo) || GaeaCommonUtil.isNullOrEmpty(deptId)) {
            return false;
        } else {
            attributes.put("userId", deptId + "-" + policeNo);
            attributes.put("deptId", deptId);
            attributes.put("policeNo", policeNo);
            attributes.put("policeName", request.getParameter("policeName"));
            attributes.put("isMobile", request.getParameter("isMobile"));
            attributes.put("userLevel", request.getParameter("userLevel"));
            return true;
        }
    }

    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {

    }
}
